package cn.me.alphamq.common.msg;

import cn.me.alphamq.common.constant.GlobalConstant;
import cn.me.alphamq.common.enumeration.EventCodeEnum;

import java.util.Arrays;

/**
 * tcp 连接中的消息对象
 *
 * @author f
 */
public class TcpMsg {

    /**
     * 最短的 msg 的长度，为 2 + 4 + 4 = 10，msg 的长度应该大于或等于这个数
     */
    public static final int MIN_LEN = 10;

    /**
     * 魔数，用于校验消息是否合法
     */
    private short magic;

    /**
     * 业务码，表示请求包的具体含义
     *
     * @see EventCodeEnum
     */
    private int code;

    /**
     * 消息的长度
     */
    private int len;

    /**
     * 消息的主体
     */
    private byte[] body;

    public TcpMsg() {
    }

    public TcpMsg(EventCodeEnum eventCodeEnum) {
        // 默认需要给 body 赋值，否则无法接收到这个 TcpMsg
        this(eventCodeEnum, new byte[0]);
    }

    public TcpMsg(EventCodeEnum eventCodeEnum, byte[] body) {
        this(eventCodeEnum.getCode(), body);
    }

    public TcpMsg(int code, byte[] body) {
        this.magic = GlobalConstant.MAGIC_NUM;
        this.code = code;
        this.len = body.length;
        this.body = body;
    }

    public short getMagic() {
        return magic;
    }

    public void setMagic(short magic) {
        this.magic = magic;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getLen() {
        return len;
    }

    public void setLen(int len) {
        this.len = len;
    }

    public byte[] getBody() {
        return body;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return "TcpMsg{" +
                "magic=" + magic +
                ", code=" + code +
                ", len=" + len +
                ", body=" + Arrays.toString(body) +
                '}';
    }
}
